package com.gx.controller;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.gx.aspect.annotation.OperationLogger;
import com.gx.domain.SysFileDetail;
import com.gx.domain.vo.ImageVo;
import com.gx.page.TableDataInfo;
import com.gx.response.R;
import com.gx.service.api.FastdfsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.List;

@Api(value = "文件操作接口", tags = "文件操作接口")
@RestController
@RequestMapping("/files")
public class FileController extends BaseController {

    @Autowired
    private FastdfsService fastdfsService;

    @ApiOperation(value = "查看文件列表", notes = "", tags = "查看文件列表")
    @OperationLogger(option = "查询文件列表")
    @GetMapping
    public R list() {
        startPage();
        List<SysFileDetail> sysFileDetails = fastdfsService.queryList();
        TableDataInfo dataTable = getDataTable(sysFileDetails);
//        return getDataTable(sysFileDetails); // 也可以直接返回TableDataInfo
        return R.ok().put("rows", dataTable.getRows()).put("total", dataTable.getTotal());
    }

    @ApiOperation(value = "查询图库列表", notes = "", tags = "查询图库列表")
    @OperationLogger(option = "查询图库列表")
    @GetMapping("/images")
    public R images() {
        ImageVo imageVo = fastdfsService.queryImage();
        return R.ok().put("images", imageVo);
    }

    @GetMapping("/download1/{id}")
    public R download(@PathVariable("id") Long id) {
        String s = fastdfsService.downloadFileLByFileDetailId(id);
        return R.ok(s);
    }

    /**
     * 多文件上传
     *
     * @param files
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "文件上传", notes = "必须传入文件，可传入文件容器，文件类别，文件描述等信息", tags = "文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "缓存key值", required = true, dataType = "MultipartFile[]", paramType = "query"),
            @ApiImplicitParam(name = "containerId", value = "归属容器id", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "fileCategory", value = "文件类别", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "description", value = "文件描述", required = false, dataType = "String", paramType = "query"),
    })
    @OperationLogger(option = "文件上传")
    @PostMapping(value = "/upload")
    public boolean uploadFilesWithFastdfs(@RequestParam("file") MultipartFile[] files, @RequestParam(value = "containerId", required = false) String containerId, @RequestParam(value = "fileCategory", required = false) String fileCategory, @RequestParam(value = "description", required = false) String description) throws IOException {
        for (int i = 0; i < files.length; i++) {
            MultipartFile multipartFile = files[i];
            String fileName = multipartFile.getOriginalFilename();
            String name = fileName.substring(0, fileName.lastIndexOf("."));
            StorePath storePath = fastdfsService.uploadFileAndUpdateFileDetail(multipartFile.getInputStream(), name, multipartFile.getSize(), fileName.substring(fileName.lastIndexOf(".") + 1), null, fileCategory, description, null);
        }
        return true;
    }

    /**
     * 单文件下载
     *
     * @param id
     * @param httpServletResponse
     * @throws MalformedURLException
     */
    @ApiOperation(value = "单个文件下载", notes = "需要传入下载文件id", tags = "单个文件下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "传入下载文件id", required = true, dataType = "Long", paramType = "path"),
    })
    @OperationLogger(option = "单个文件下载")
    @GetMapping(value = "/download/{id}")
    public void downloadFilesWithFastdfs(@PathVariable Long id, HttpServletResponse httpServletResponse) throws MalformedURLException {
        SysFileDetail sysFileDetail = fastdfsService.queryFileDetail(id);

        if (sysFileDetail != null) {
            try {
                String fileName = URLEncoder.encode(sysFileDetail.getLogicalName(), "UTF8");
                String fileUrl = sysFileDetail.getServerRootDir();
                String filepath = StringUtils.substringAfter(sysFileDetail.getServerRootDir(), sysFileDetail.getServerGroup() + File.separator);
                DownloadByteArray callback = new DownloadByteArray();
                byte[] bytes = fastdfsService.getStorageClient().downloadFile(sysFileDetail.getServerGroup(), filepath, callback);
                httpServletResponse.reset();
                httpServletResponse.setContentType("application/x-download");
                httpServletResponse.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "." + sysFileDetail.getExtentionName() + "\"");
                httpServletResponse.getOutputStream().write(bytes);
                fastdfsService.downloadFileLByFileDetailId(id);
                httpServletResponse.getOutputStream().close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
